<?php
/**
 * Mysql.php
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@mygem.org so we can send you a copy immediately.
 *
 * @copyright   Copyright (c) 2012, MyGem <info@mygem.org>
 * @package     MyGem\Db
 */


class MyGem_Db_Mysql extends MyGem_Db_Abstract
{

    protected function _connect()
    {
        $this->connection = mysql_connect($this->hostname, $this->username, $this->password);
        if (!$this->connection)
        {
            $error = mysql_error();
            trigger_error($error);
            $this->errors[] = $error;
        }
        if ($this->connection)
        {
            $select_db = mysql_select_db($this->dbname, $this->connection);
            if (!$select_db)
            {
                $error = mysql_error();
                trigger_error($error);
                $this->errors[] = $error;
            }
        }
    }

    public function escape($value)
    {
        return mysql_escape_string($value);
    }

    public function select($sql)
    {
        $rows = array();
        $result = $this->query($sql);
        if (!$result) return $rows;
        while ($row = mysql_fetch_assoc($result))
        {
            $rows[] = $row;
        }
        return $rows;
    }

    public function selectSingle($sql)
    {
        $ret = array();
        $result = $this->query($sql);
        if (!$result) return $ret;
        if ($row = mysql_fetch_assoc($result)) $ret = $row;
        return $ret;
    }

    public function query($sql)
    {
        if ($this->connection === null) { // try reconnecting
            $this->_connect();
        }
        $result = mysql_query($sql, $this->connection);
        if (!$result)
        {
            $error = mysql_error();
            trigger_error($error);
            trigger_error(print_r(debug_backtrace(),true));
            $this->errors[] = $error;
        }
        return $result;
    }

    public function lastInsertId()
    {
        return mysql_insert_id();
    }

}
